package com.training.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.training.entity.RoleUser;
import com.training.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName: LoginController
 * Package: com.training.controller
 * Description: 公众监督员登录与退出
 * @Author: wfz
 * @Create: 2024-06-07 - 10:45
 * @Version: v1.0
 */


@RestController
@Tag(name = "公众监督员登录控制器")
public class LoginController {

    @Operation(summary = "公众监督员登录")
    @PostMapping("/login")
    public SaResult login(@RequestBody User user) {
        //查询user表和user_role表，找到code为user.getCode()的用户
        User userOne = Db.lambdaQuery(User.class).eq(User::getCode, user.getCode()).oneOpt()
                .orElseThrow(() -> new RuntimeException("账号不存在"));
        Db.lambdaQuery(RoleUser.class).eq(RoleUser::getUserId, userOne.getId()).eq(RoleUser::getRoleId, 3).oneOpt()
                .orElseThrow(() -> new RuntimeException("非公众监督员账号"));
        if(!userOne.getPassword().equals(user.getPassword())){
            throw new RuntimeException("密码错误");
        }
        //登录
        StpUtil.login(userOne.getId());
        return SaResult.ok(userOne.getId());
    }

    @Operation(summary = "公众监督员注销")
    @PostMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("注销成功");
    }

    @Operation(summary = "公众监督员注册")
    @PostMapping("/register")
    public SaResult register(@RequestBody User user) {
        User userOne = Db.lambdaQuery(User.class).eq(User::getCode, user.getCode()).oneOpt().orElse(null);
        if (userOne != null) {
            return SaResult.error("账号已存在");
        }
        boolean save = Db.save(user);
        RoleUser userRole = new RoleUser();
        userRole.setUserId(user.getId());
        userRole.setRoleId("3");
        Db.save(userRole);
        if (save) {
            return SaResult.ok("注册成功");
        }
        return SaResult.error("注册成功");
    }
}